﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

[Hotfix]
public class EnemyController : MonoBehaviour
{
	#region 单例模型
	private static EnemyController singleton;
	private EnemyController() { }
	private void Awake() { singleton = this; }
	public static EnemyController Singleton { get => singleton; }
	#endregion

	[LuaCallCSharp]
	public void Test() {
		StartCoroutine(CreateEnemy(2, number));
		Debug.Log("dasdasd");
	}

	[Header("怪物预制物")]
	public Enemy enemyPrefab;
	// [Header("怪物的最大数量")]
	// public int number;

	[Header("怪物的父物体")]
	public Transform enemyPools;

	[Header("所有生成的怪物")]
	public List<Enemy> enemys = new List<Enemy>();

	[Header("怪物的总数")]
	public int number;
	public int delNum;  // 所有消灭的怪物

	private void Start() {
		// StartCoroutine(CreateEnemy(2, 5));
	}

	/// <summary>
	/// Tower获取范围内怪物
	/// </summary>
	/// <param name="center"></param>
	/// <param name="range"></param>
	/// <returns></returns>
	public Enemy[] GetEnemyInRange(Vector3 center, float range) {
		List<Enemy> es = new List<Enemy>();
		foreach (Enemy enemy in enemys) {
			if (Vector3.Distance(enemy.transform.position, center) <= range)
				es.Add(enemy);
		}
		return es.ToArray();
	}


	/// <summary>
	/// 间隔时间time, 怪物总数number
	/// </summary>
	/// <param name="time"></param>
	/// <param name="number"></param>
	/// <returns></returns>
	public IEnumerator CreateEnemy(float time, int number) {
		while (true) {
			yield return new WaitForSeconds(time);
			Enemy enemy = Instantiate(enemyPrefab, enemyPools);
			enemys.Add(enemy);
			if (GameController.Singleton.JudgeGameOver()) {
				break;
			}
			if (--number <= 0) break;
		}
	}





	/// <summary>
	/// 点击Button生成怪物事件
	/// </summary>
	public void CreateEnemyClick(Transform btn) {
		StartCoroutine(CreateEnemy(2, number));
		// Debug.Log(number);
		GameController.Singleton.AddEnemyCount(number);
		btn.gameObject.SetActive(false);
	}

	public void DeleteEnemy(Enemy enemy) {
		for (int i = 0; i < enemys.Count; i++) {
			if (enemys[i] == enemy) {
				enemys.Remove(enemy);
				Destroy(enemy.gameObject);
				break;
			}
		}
	}
}
